import redis

import json
import redis
from datetime import datetime

# 自定义 JSON 编码器，用于处理 datetime 对象
class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        return super().default(obj)

# 自定义 JSON 解码器，用于将字符串转换回 datetime 对象
def datetime_decoder(dct):
    for key, value in dct.items():
        try:
            dct[key] = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
        except (ValueError, TypeError):
            pass
    return dct

class gpRedisHelper:
    def __init__(self, host='localhost', port=6379, db=0):
        self.r = redis.Redis(host=host, port=port, db=db)

    def set(self, key, value):
        # 将对象转换为 JSON 字符串
        json_value = json.dumps(value, cls=DateTimeEncoder)
        self.r.set(key, json_value)

    def get(self, key):
        # 从 Redis 读取 JSON 字符串
        stored_json = self.r.get(key)
        if stored_json is None:
            return None
        # 将 JSON 字符串转换回对象
        stored_json = stored_json.decode('utf-8')
        return json.loads(stored_json, object_hook=datetime_decoder)

class gpRedis():
    def __init__(self, host_addr='localhost'):
        self.redis_server = host_addr

    def get(self, keyname):
        # ���ӵ� Redis ������
        r = redis.Redis(host=self.redis_server, port=6379, db=0)
        
        # ����Ĵ������ƣ�������
        register_name = keyname
        
        # �� Redis �ж�ȡ�Ĵ�����ֵ
        register_value = r.get(register_name)
        
        return register_value

    def set(self, keyname, value):
        if(self.get(keyname) != value):
            # ���ӵ� Redis ������
            r = redis.Redis(host=self.redis_server, port=6379, db=0)
            # ����Ĵ������ƣ�������
            register_name = keyname
            # �� Redis �ж�ȡ�Ĵ�����ֵ
            r.set(register_name, value)

    def clear(self, keyname):
        try:
            # ���ӵ� Redis ������
            r = redis.Redis(host=self.redis_server, port=6379, db=0)
            
            # ����Ĵ������ƣ�������
            register_name = keyname
            
            # �� Redis �ж�ȡ�Ĵ�����ֵ
            r.delete(register_name)
        except:
            i = i+1